﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Qero.ChartPoint
{
    /// <summary>
    /// Interaction logic for AppSetup.xaml
    /// </summary>
    public partial class AppSetup : UserControl
    {
        public AppSetup()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.DataContext = MetaUnit.BuildCharter();
        }

        private Charter GetMainContext()
        {
            if ((this.DataContext == null) || (!this.DataContext.GetType().Equals(typeof(Charter)))) return null;

            return (Charter)this.DataContext;
        }

#region :: Get Controls ::
        
        private Button SenderButton(object objControl)
        {
            return ((objControl != null) && (objControl.GetType().Equals(typeof(Button)))) ? (Button)objControl : null;
        }

        private TextBox SenderTextbox(object objControl)
        {
            return ((objControl != null) && (objControl.GetType().Equals(typeof(TextBox)))) ? (TextBox)objControl : null;
        }

        private ComboBox SenderCombox(object objControl)
        {
            return ((objControl != null) && (objControl.GetType().Equals(typeof(ComboBox)))) ? (ComboBox)objControl : null;
        }

        private TextBox GetListItemTextbox(ListBoxItem lookListItem)
        {
            if (lookListItem == null) return null;

            return BaseUnit.GetChildControl<TextBox>(lookListItem, string.Empty);
        }

        private Button GetListItemButton(ListBoxItem lookListItem, string controlName)
        {
            if (lookListItem == null) return null;

            return BaseUnit.GetChildControl<Button>(lookListItem, controlName);
        }

        private ComboBox GetListItemCombox(ListBoxItem lookListItem, string controlName)
        {
            if (lookListItem == null) return null;

            return BaseUnit.GetChildControl<ComboBox>(lookListItem, controlName);
        }

        private TextBlock GetListItemTxtblck(ListBoxItem lookListItem, string controlName)
        {
            if (lookListItem == null) return null;

            return BaseUnit.GetChildControl<TextBlock>(lookListItem, controlName);
        }

        private Border GetListItemBorder(ListBoxItem lookListItem, string controlName)
        {
            if (lookListItem == null) return null;

            return BaseUnit.GetChildControl<Border>(lookListItem, controlName);
        }

#endregion :: Get Controls ::

#region :: chartTable actions ::

        private void NewChart_Click(object sender, RoutedEventArgs e)
        {
            UpdateChartTable();

            chartTable.SelectedIndex = 0;
        }

        /// <summary> Перехват нажатия "Enter" в поле ввода названия
        /// </summary>
        private void ChartName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Return) return;
            
            ComboBox selectSub = GetListItemCombox(GetChlistItem(SenderTextbox(sender)), "selectSub");

            if (selectSub != null) selectSub.Focus();
        }

        /// <summary> Перехват нажатия "Enter" в поле выбора директории
        /// </summary>
        private void ChartDir_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Return) return;

            ComboBox selectFile = GetListItemCombox(GetChlistItem(SenderCombox(sender)), "selectFile");

            if (selectFile != null) selectFile.Focus();
        }

        /// <summary> Перехват нажатия "Enter" в поле разрешения прикрепления файлов
        /// </summary>
        private void ChartFile_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Return) return;

            TextBox getChartText = GetListItemTextbox(GetChlistItem(SenderCombox(sender)));

            if (getChartText != null) getChartText.Focus();
        }

        private void ChartName_LostFocus(object sender, RoutedEventArgs e)
        {
            //CheckChartSave(GetChlistItem(SenderTextbox(sender)));
        }

        private void ChartDir_LostFocus(object sender, RoutedEventArgs e)
        {
            CheckChartSave(GetChlistItem(SenderCombox(sender)));
        }

        private void ChartFile_LostFocus(object sender, RoutedEventArgs e)
        {
            CheckChartSave(GetChlistItem(SenderCombox(sender)));
        }

        private void SaveChart_Click(object sender, RoutedEventArgs e)
        {
            Button getSaveChart = SenderButton(sender);

            if ((getSaveChart == null) || (getSaveChart.DataContext == null) || (!getSaveChart.DataContext.GetType().Equals(typeof(ChartTable)))) return;

            ChartTable savedChart = (ChartTable)getSaveChart.DataContext;

            int savedChartIndex = chartTable.SelectedIndex;

            MetaUnit.UpdateChart(savedChart);

            UpdateChartTable(savedChart, savedChartIndex);
        }

        private void CheckChartSave(ListBoxItem chartListItem)
        {
            if (chartListItem == null) return;

            Button getSaveChart = GetListItemButton(chartListItem, "getSaveChart");

            if (getSaveChart != null) getSaveChart.IsEnabled = ((ChartTable)chartListItem.DataContext).readyToSave;
        }

        private void UpdateChartTable()
        {
            ChartTable newChartTable = new ChartTable();
            newChartTable.ReadyToEdit();

            UpdateChartTable(newChartTable, 0);
        }

        private void UpdateChartTable(ChartTable insChart, int insIndex)
        {
            if ((this.DataContext == null) || (!this.DataContext.GetType().Equals(typeof(Charter)))) return;

            if (insIndex == 0) insChart.chartMake = true;

            Charter updCharter = new Charter();
            updCharter.ChartSet = (from il in ((Charter)this.DataContext).ChartSet where il.chartUid != insChart.chartUid select il).ToList<ChartTable>();
            updCharter.ChartSet.Insert(insIndex, insChart);

            if ((insIndex == 0) && (updCharter.ChartSet.Count > 1)) updCharter.ChartSet[1].chartMake = null;

            this.DataContext = updCharter;
        }

        private ListBoxItem GetChlistItem(Control actControl)
        {
            if (actControl == null) return null;

            return (ListBoxItem)chartTable.ItemContainerGenerator.ContainerFromItem(actControl.DataContext);
        }

#endregion :: chartTable actions ::

#region :: chartField actions ::
        
        private void NewField_Click(object sender, RoutedEventArgs e)
        {
            UpdateChartField();

            int tmpIndex = chartTable.SelectedIndex;

            chartTable.SelectedIndex = -1;

            chartTable.SelectedIndex = tmpIndex;
            chartField.SelectedIndex = 0;
        }

        private void FieldName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Return) return;

            ComboBox selectType = GetListItemCombox(GetFldlistItem(SenderTextbox(sender)), "selectType");

            if (selectType != null) selectType.Focus();
        }

        private void FieldName_LostFocus(object sender, RoutedEventArgs e)
        {
            CheckFieldSave(GetFldlistItem(SenderTextbox(sender)));
        }

        private void FieldType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox selectType = SenderCombox(sender);

            if ((selectType == null) || (selectType.SelectedItem == null) || (!selectType.SelectedItem.GetType().Equals(typeof(string)))) return;

            Charter setupCharter = GetMainContext();

            if (setupCharter == null) return;

            ListBoxItem chartFieldItem = GetFldlistItem(selectType);

            TextBlock additionCapt = GetListItemTxtblck(chartFieldItem, "additionCapt");

            int selectTypeId = Array.IndexOf(setupCharter.fieldsTypes, (string)selectType.SelectedItem);

            if ((additionCapt == null) || (selectTypeId <= 0)) return;

            additionCapt.Text = setupCharter.additionCapts[selectTypeId];

            Border subBorder = GetListItemBorder(chartFieldItem, "subBorder");

            if (subBorder == null) return;

            subBorder.Visibility = (selectTypeId != 2 && selectTypeId != 6) ? Visibility.Visible : Visibility.Hidden;

            ComboBox selectSub = GetListItemCombox(chartFieldItem, "selectSub");

            if (selectSub != null)
            {
                selectSub.Visibility = (selectTypeId == 1 || selectTypeId == 3 || selectTypeId == 7) ? Visibility.Visible : Visibility.Hidden;
                selectSub.IsReadOnly = (selectTypeId != 3);
            }
        }

        private void SaveField_Click(object sender, RoutedEventArgs e)
        {
            Button getSaveField = SenderButton(sender);

            if ((getSaveField == null) || (getSaveField.DataContext == null) || (!getSaveField.DataContext.GetType().Equals(typeof(ChartField)))) return;

            ChartField savedField = (ChartField)getSaveField.DataContext;

            int savedChartIndex = chartTable.SelectedIndex, savedFieldIndex = chartField.SelectedIndex;
        }

        private void CheckFieldSave(ListBoxItem fieldListItem)
        {
            if (fieldListItem == null) return;

            Button getSaveField = GetListItemButton(fieldListItem, "getSaveField");

            if (getSaveField != null) getSaveField.IsEnabled = ((ChartField)fieldListItem.DataContext).readyToSave;
        }

        private void UpdateChartField()
        {
            ChartField newChartField = new ChartField();
            newChartField.ReadyToEdit();

            UpdateChartField(newChartField, 0);
        }

        private void UpdateChartField(ChartField insField, int insIndex)
        {
            if ((this.DataContext == null) || (!this.DataContext.GetType().Equals(typeof(Charter)))) return;

            if ((chartTable.SelectedItem == null) || (!chartTable.SelectedItem.GetType().Equals(typeof(ChartTable)))) return;

            if (insIndex == 0) insField.chartMake = true;

            Charter updCharter = new Charter();
            updCharter.ChartSet = (from il in ((Charter)this.DataContext).ChartSet select il).ToList<ChartTable>();

            ChartTable updChart = updCharter.GetChartByUid(((ChartTable)chartTable.SelectedItem).chartUid);
            updChart.FieldSet.Insert(insIndex, insField);

            if ((insIndex == 0) && (updChart.FieldSet.Count > 1)) updChart.FieldSet[1].chartMake = null;

            this.DataContext = updCharter;

            chartTable.SelectedItem = updChart;
        }

        private ListBoxItem GetFldlistItem(Control actControl)
        {
            if (actControl == null) return null;

            return (ListBoxItem)chartField.ItemContainerGenerator.ContainerFromItem(actControl.DataContext);
        }

#endregion :: chartField actions ::

        /// <summary> Добавляем опцию по Enter'у после ввода строки
        /// </summary>
        private void selectSub_KeyDown(object sender, KeyEventArgs e)
        {
            ComboBox selSubCombo = SenderCombox(sender);

            if (selSubCombo == null || selSubCombo.IsReadOnly || e.Key != Key.Return) return;
        }

        /// <summary> Прибиваем опцию по дабл-клику, но только если выбрана существующая опция
        /// </summary>
        private void selectSub_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ComboBox selSubCombo = SenderCombox(sender);

            if (selSubCombo == null || selSubCombo.IsReadOnly || selSubCombo.SelectedIndex < 0) return;
        }

    }
}